import dayjs from 'dayjs'
import { Http } from './Api'
import { GetIndexedDB, AddIndexdDB, IndexedDBClear } from './IndexedDB'
// TODO 判断浏览器版本
export const judgeBrowserVersion = () => {
    const browserVersions = { Chrome: 93, Safari: 530, Firefox: 92, Opera: 80 }
    const { userAgent } = window.navigator
    const webList = userAgent.split(' ').filter(v => v.indexOf('/') !== -1 && v.indexOf('Mozilla') === -1 && v.indexOf('AppleWebKit') === -1)
    let currentVersions = {}
    for (const key of webList) {
        const [keyName, value] = key.split('/')
        currentVersions[keyName] = parseInt(value)
    }
    return Object.keys(browserVersions).every(key => {
        if (currentVersions[key] && browserVersions[key]) { return currentVersions[key] >= browserVersions[key] }
        return true
    })
}

// TODO Debug函数
export const debuggerFun = () => {
    const block = () => {
        if (window.outerHeight - window.innerHeight > 200 || window.outerWidth - window.innerWidth > 200) {
            document.body.innerHTML = "检测到非法调试,请关闭后刷新重试!";
            sessionStorage.clear()
            localStorage.clear()
        }
        setInterval(() => {
            (function () { return false }
            // eslint-disable-next-line no-unexpected-multiline
            ['constructor']('debugger')
            // eslint-disable-next-line no-unexpected-multiline
            ['call']())
        }, 50)
    }
    try { block() } catch (err) { /* empty */ }
}


// Todo 获取树中某一字段的详细信息
export const treeValue = (tree, value, key = 'uuid') => {
    for (let i = 0; i < tree.length; i++) {
        if (tree[i][key] === value) {
            return tree[i]
        } else if (tree[i].children && tree[i].children.length) {
            const result = treeValue(tree[i].children, value, key)
            if (result) return result
        }
    }
    return null
}
// Todo 获取对象数组中某一段的详细信息
export const objectArrValue = (arr, value, key = 'uuid') => {
    return arr.find(obj => obj[key] === value);
}
// Todo 判断某一个字段是否在对象数组中
export const objectArrHas = (arr, value, key = 'uuid') => {
    return arr.some(obj => obj[key] === value);
}

// Todo Form表单时间处理后函数(提交时触发)
export const formTempDateHandleBefore = (format, date) => {
    return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
    // const { picker, showTime, format } = field
    // if (picker) {
    //     const pickerMapping = { year: 'YYYY', month: 'YYYY-MM', date: 'YYYY-MM-DD' }
    //     return dayjs(date).format(pickerMapping[picker])
    // } else if (format) {
    //     return new Date(dayjs(date).format(format.toUpperCase()))
    // }
}

// Todo 字符换转换请求体对象
export const stringToObject = (str) => {
    const newStr = str ? str
        .split('&')
        .map(pair => pair.split('='))
        .map(([key, value]) => [decodeURIComponent(key), decodeURIComponent(value)])
        .reduce((obj, [key, value]) => {
            obj[key] = value
            return obj
        }, {}) : ''
    return newStr
}


// Todo 用key获取指定数据
export const findDataByKey = (object, value, key = 'uuid') => {
    for (const date in object) {
        const events = object[date]
        for (const event of events) { if (event[key] === value) { return event } }
    }
    return null
}
// Todo 用key替换指定对象
export const replaceDataByKey = (data, newEvent, value, key = 'uuid') => {
    for (let i = 0; i < data.length; i++) {
        if (data[i][key] === value) data[i] = newEvent
    }
    return data;
}
// Todo 用key删除指定对象
export const deleteDateByKey = (data, value, key = 'uuid') => {
    for (let date in data) {
        const events = data[date]
        data[date] = events.filter(event => event[key] !== value)
    }
    return data
}

// Todo 根据 key 替换树形结构的指定值
export const updateTreeByKey = (obj, uuid, newData, key = 'uuid', value = 'label') => {
    for (const item of obj) {
        if (item[key] === uuid) item[value] = newData
        if (item.children) updateTreeByKey(item.children, uuid, newData, key, value);
    }
}

// Todo 根据 key 删除树形结构中的对象
export const removeTreeByKey = (obj, value, key = 'uuid') => {
    return obj.filter(item => {
        if (item.children) item.children = removeTreeByKey(item.children, value, key)
        return item[key] !== value
    })
}

// Todo 获取树形数据的所有指定值并返回一维数据
export const getTreeKeys = (tree, key = 'key') => {
    const keys = []
    const traverse = (tree) => {
        if (tree.key !== undefined) keys.push(tree.key)
        if (tree.children && tree.children.length > 0) tree.children.forEach(child => traverse(child))
    }
    tree.forEach(node => traverse(node))
    return keys
}

// Todo 删除对象控制
export const removeObjectEmpty = (obj) => {
    return Object.fromEntries(
        Object.entries(obj).filter(([key, value]) => {
            return value !== null && value !== undefined && value !== '' && !Array.isArray(value) || value?.length > 0;
        })
    )
}

// Todo 删除多想多个键
export const removeObjectObj = (obj1, obj2) => {
    const entries = Object.entries(obj1).filter(([key]) => !obj2.hasOwnProperty(key));
    return Object.fromEntries(entries);
}

// Todo 根据url尾缀判断文件类型
export const getFileTypeFromUrl = (url) => {
    const parts = url.split('.')
    const extension = parts.at(-1).toLowerCase()
    switch (extension) {
        case 'jpg': case 'jpeg': case 'png': case 'gif': case 'bmp': case 'svg': return 'image'
        case 'mp4': case 'avi': case 'mov': case 'mkv': return 'video'
        case 'pdf': case 'doc': case 'docx': case 'xls': case 'xlsx': case 'ppt': case 'pptx': case 'txt': case 'md': return 'edge'
        default: return 'not'
    }
}

export const strOfurlParamsFunc = (string) => {
    if (string) {
        const data = string.split('&').reduce((acc, item) => {
            const [key, value] = item.split('=')
            acc[key] = value
            return acc
        }, {})
        return data
    } else return {}
}

// Todo 登录回调
export const getSignUpBack = async (data) => {
    const key = await GetIndexedDB('key')
    const project = await GetIndexedDB('project')
    try {
        await AddIndexdDB('token', data)
        const menu = await Http({ url: 'getRoleMenuListByUserUuid' })
        await AddIndexdDB('menu', menu.data.list)
        const user = await Http({ url: 'getUserInfo' })
        await AddIndexdDB('user', user.data)
        const power = await Http({ url: 'getRoleMenu' })
        await AddIndexdDB('power', power.data)
        await AddIndexdDB('openKey', 'a0b4f6b8-ef44-4b43-925f-85a299eb52cb')
        await AddIndexdDB('pageList', [{ key: 'a0b4f6b8-ef44-4b43-925f-85a299eb52cb', label: '首页', url: 'Home', icon: 'shou', closable: false }])
        return { menu: menu.data.list, user: user.data }
    } catch (err) {
        IndexedDBClear()
        await AddIndexdDB('key', key)
        await AddIndexdDB('project', project)
        return false
    }
}

export const numberFormatting = (type, data) => {
    const typeMapping = { f: 'fixedPoint', d: 'decimal', p: 'percent', c: 'currency' }
    if (!data || type !== 'number') return data
    const parts = data.match(/^([a-zA-Z])(\d+)$/)
    if (!parts) return data
    const [_, prefix, numStr] = parts
    const formatType = typeMapping[prefix.toLowerCase()]
    if (!formatType) return data
    const precision = Number.parseInt(numStr, 10)
    if (Number.isNaN(precision)) return data
    return prefix.toLowerCase() === 'c' ?
        { style: "currency", currency: "CNY", useGrouping: true, precision } :
        { type: formatType, precision }
}